package dbcontrol

import (
	"MqttCloudProtocolServer/publiclib/define"
	"MqttCloudProtocolServer/publiclib/helplib"
	"database/sql"
	"errors"
	"fmt"
	"sync"

	_ "modernc.org/sqlite"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
)

var db *dbConnection
var syncLocker = new(sync.Mutex)

//getDBContent 获取数据库连接
func getDBContent() *dbConnection {
	syncLocker.Lock()
	if db == nil {
		db = new(dbConnection)
	}
	syncLocker.Unlock()
	return db
}

type dbConnection struct {
	engine *xorm.Engine
}

//DBCon 执行sql命令使用
type DBCon struct {
	dbConnection
}

//ExecuteSQL 执行SQL命令
func (_this *DBCon) ExecuteSQL(sql string) (sql.Result, error) {
	if _this.engine != nil {
		return _this.engine.Exec(sql)
	}
	return nil, errors.New("没有数据库连接")
}

func (_this *dbConnection) GetConnection() (*xorm.Engine, error) {
	if _this.engine == nil {
		fmt.Println(define.ConfigPath + "config.db")
		if res, err := helplib.FileExists(define.ConfigPath + "config.db"); !res {
			println("文件不存在")
			return nil, errors.New(err.Error() + "-文件不存在")
		}
		var engine *xorm.Engine
		var err error
		if engine, err = xorm.NewEngine("sqlite", define.ConfigPath+"config.db"); err != nil {
			println(err)
			return nil, err
		}
		engine.ShowSQL(true)
		switch define.RunLogConsoleLevel {
		case 0:
			engine.SetLogLevel(log.LOG_OFF)
		case 1:
			engine.SetLogLevel(log.LOG_UNKNOWN)
		case 2:
			engine.SetLogLevel(log.LOG_ERR)
		case 3:
			engine.SetLogLevel(log.LOG_WARNING)
		case 4:
			engine.SetLogLevel(log.LOG_INFO)
		case 5:
			engine.SetLogLevel(log.LOG_DEBUG)
		case 6:
			engine.SetLogLevel(log.LOG_DEBUG)
		default:
			engine.SetLogLevel(log.LOG_OFF)
		}
		/*if err := engine.Sync2(new(dborm.Modeenum), new(dborm.Mqttconf),
			new(dborm.Mqttserver), new(dborm.Protocolenum),
			new(dborm.Tcpconf), new(dborm.Userconf), new(dborm.Userserver)); err != nil {
			return nil, err

		}*/
		_this.engine = engine
	}
	return _this.engine, nil
	//engine.ShowWarn(true)
}
func (_this *dbConnection) CloseConnection() error {
	return _this.engine.Close()
}
